package com.xiaomazi.acl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomazi.acl.entity.Role;
import com.xiaomazi.acl.entity.User;
import com.xiaomazi.acl.entity.UserRole;
import com.xiaomazi.acl.mapper.RoleMapper;
import com.xiaomazi.acl.service.RoleService;
import com.xiaomazi.acl.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: llxy-parent
 * @description: 角色业务类
 * @author: 小马子
 * @create: 2023-03-21 11:10
 **/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 根据用户id获取角色
     * @param id userId
     * @return List<Role>
     */
    @Override
    public List<String> selectRoleByUserId(String id) {
        return baseMapper.selectRoleByUserId(id);
    }

    /**
     * 根据用户获取角色数据
     * @param userId userId
     * @return Map<String, Object>
     */
    @Override
    public Map<String, Object> findRoleByUserId(String userId) {
        Map<String, Object> roleMap = new HashMap<>();
        List<Role> allRolesList = this.list();

        List<UserRole> userRoleList = userRoleService.selectByUserId(userId);
        List<String> roleIds = userRoleList.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());

        List<Role> assignRoles = new ArrayList<>();
        allRolesList.forEach(role -> {
                    if (roleIds.contains(role.getId())){
                        assignRoles.add(role);
                    }
                });

        roleMap.put("assignRoles",assignRoles);
        roleMap.put("allRolesList",allRolesList);
        return roleMap;
    }

    /**
     * 根据用户分配多个角色
     * @param userId 用户id
     * @param roleId 角色id
     */
    @Override
    public void saveUserRoleRealtionShip(String userId, String[] roleIds) {
        userRoleService.update().eq("user_id",userId).remove();

        List<UserRole> userRoleList = new ArrayList<>();
        for (String roleId : roleIds) {
            if (StrUtil.isBlank(roleId)) continue;
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);

            userRoleList.add(userRole);
        }

        userRoleService.saveBatch(userRoleList);
    }
}
